package fr.epsi.spring1.servlets;

import java.io.IOException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import fr.epsi.spring1.dao.CommandeDao;
import fr.epsi.spring1.dao.UserDao;
import fr.epsi.spring1.dao.impl.CommandeDaoPooledImpl;
import fr.epsi.spring1.dao.impl.UserDaoPooledImpl;
import fr.epsi.spring1.domain.Commande;
import fr.epsi.spring1.domain.User;

/**
 * Servlet implementation class Commande
 */
@WebServlet("/Commande")
public class CommandeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public CommandeServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		this.process(request, response);
	}

	public void process(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String commande = request.getParameter("commande");

		Logger.getRootLogger().debug("Login " + commande);

		RequestDispatcher rd;

		if (("commandeEnCours").equals(commande)) {

			UserDao userDao = new UserDaoPooledImpl();
			User user = userDao.getUser((String) request.getSession()
					.getAttribute("login"));

			CommandeDao commandeDao = new CommandeDaoPooledImpl();
			List<Commande> listeCommandes = commandeDao.select(user);

			request.setAttribute("login",
					request.getSession().getAttribute("login"));
			request.setAttribute("lesCommandes", listeCommandes);

			rd = getServletContext().getRequestDispatcher(
					"/commandeEnCours.jsp");
			rd.include(request, response);

		} else {
			rd = getServletContext().getRequestDispatcher("/accueil.jsp");
			rd.include(request, response);
		}

	}
}
